<template>
  <div id="earlywarning">
    <div v-if="data" v-cloak>
      <div class="homeTitle">今日指标预警情况</div>
      <div class="echartsbox">
        <div id="myChart" class="circle"></div>
      </div>
    </div>
    <div class="query">
      <div class="query">
        <!-- --------------- -->
        <div class="sTitle">
          <span>指标预警信息</span>
          <el-input placeholder="搜索行社\机构" v-model="search" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="queryTable(1)"></el-button>
          </el-input>
        </div>
        <div class="queryCon">
          <div class="qSeles">
            <!-- 两个选择 -->
            <div class="xuanze">
              <div class="xuanzeCon">
                <span>选择行社\机构：</span>
                <el-tooltip :content="banks? banks: '未选择任何行社/机构'" placement="top">
                  <el-button size="small" @click="morechoose">点击进行多选</el-button>
                </el-tooltip>
              </div>
              <div class="xuanzeCon">
                <span>选择指标：</span>
                <el-tooltip :content="zhibiao? zhibiao: '未选择任何指标'" placement="top">
                  <el-button size="small" @click="choosezhibiao">点击进行多选</el-button>
                </el-tooltip>
              </div>
              <div class="xuanzeCon">
                <span>我关注的：</span>
                <el-select v-model="value" placeholder="请选择" size="small">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.value"
                    :value="item.label"
                  ></el-option>
                </el-select>
              </div>
            </div>
            <!-- 类型 -->
            <div class="leixing">
              <div>
                <span>预警类型：</span>
              </div>
              <div class="qiek">
                <el-checkbox-group v-model="typeChek" @change="checkOne">
                  <el-checkbox
                    v-for="item in type"
                    :label="item"
                    :key="item"
                    border
                    size="small"
                  >{{item}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
            <!-- 关注级别 -->
            <div class="leixing">
              <div>
                <span>关注级别：</span>
              </div>
              <div class="qiek">
                <el-checkbox-group v-model="levelChek" @change="checkTwo">
                  <el-checkbox
                    v-for="item in level"
                    :label="item"
                    :key="item"
                    border
                    size="small"
                  >{{item}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
            <!-- 时间轴 -->
            <div class="timezhou">
              <div class="timetitle">时间轴：</div>
              <div class="block">
                <el-slider v-model="time" :min="1" :max="60" :format-tooltip="formatTooltip"></el-slider>
              </div>
            </div>
            <!-- 按钮 -->
            <div class="btnAb">
              <el-button type="primary" size="small" @click="queryTable(1)">查询</el-button>
              <el-button type="primary" size="small" @click="daochu">导出</el-button>
              <el-button type="primary" size="small" @click="queryReset">重置查询条件</el-button>
              <el-button type="primary" size="small" @click="mange">管理已关注指标</el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <div class="tablecon">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="createTime" label="预警日期" align="center" :formatter="dateTable"></el-table-column>
          <el-table-column prop="warnType" label="预警类型" align="center"></el-table-column>
          <el-table-column prop="warnBank" label="预警行社\机构" align="center"></el-table-column>
          <el-table-column prop="indicatorName" label="指标" align="center"></el-table-column>
          <el-table-column prop="restrictValue" label="监管值" align="center" :formatter="baifenbi"></el-table-column>
          <el-table-column prop="nowValue" label="当前值" align="center" :formatter="baifenbi"></el-table-column>
          <el-table-column prop="userFocusLevel" label="个人关注级别" align="center"></el-table-column>
          <el-table-column prop="address" label="操作" align="center" width="180">
            <template slot-scope="scope">
              <el-button size="mini" v-if="scope.row.state==0" @click="guanzhu(scope.row)">关注</el-button>
              <el-button
                size="mini"
                v-if="scope.row.state==1"
                @click="cancelGuanzhu(scope.row)"
              >取消关注</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pgfy">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="10"
          layout="total, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "earlywarning",
  data() {
    return {
      // 预警类型
      data: [],
      amount: [],
      exceed: [],
      remind: [],
      warnBank: [],
      alarm: [],
      search: "",
      banks: "",
      banksId: [],
      type: ["超标", "报警", "提醒", "正常"],
      typeChek: ["超标", "报警", "提醒", "正常"],
      level: ["严重", "中等", "普通", "未设定预警级别"],
      levelChek: ["严重", "中等", "普通", "未设定预警级别"],
      time: 3,
      options: [
        {
          value: "全部",
          label: ""
        },
        {
          value: "已关注",
          label: "1"
        },
        {
          value: "未关注",
          label: "0"
        }
      ],
      // 我关注的
      value: "",
      zhibiao: "",
      zhibiaoId: "",
      zhibiaoArr: [],
      tableData: [],
      // 分页
      currentPage: 1,
      total: null,
      status: this.$route.query.status
    };
  },
  created() {
    let bank = JSON.parse(sessionStorage.getItem("user")).bank;
    if (bank != "省联社") {
      this.status = false;
    } else {
      this.status = true;
    }
  },
  mounted() {
    this.getyujing();
    this.queryTable(1);
  },
  methods: {
    baifenbi(row, column) {
      return Number(row[column.property]).toFixed(2) + "%";
    },
    guanzhu(value) {
      this.$router.push({
        path: "targetDetail",
        query: { id: value.siId, title: value.indicatorName }
      });
    },
    cancelGuanzhu(value) {
      this.axios
        .post("userAttention/deleteById", { bivId: value.bivId })
        .then(({ data }) => {
          if (data.code == 200) {
            value.state == 0;
            this.$message({ message: "取消关注成功", type: "success" });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    getyujing() {
      this.axios
        .get("warnRecord/findCountByUserId")
        .then(({ data }) => {
          if (data.code == 200) {
            this.data = data.data;
            this.data.forEach((item, index) => {
              this.amount.push(item.amount);
              this.exceed.push(item.exceed);
              this.remind.push(item.remind);
              this.warnBank.push(item.warnBank);
              this.alarm.push(item.alarm);
            });
            this.drawLine(); // 初始化echars
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    drawLine() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById("myChart"));
      // 绘制图表
      myChart.setOption({
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "line" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          data: this.warnBank
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "提醒",
            type: "bar",
            stack: "总量",
            label: {
              normal: {
                show: true,
                position: "insideRight"
              }
            },
            itemStyle: {
              normal: {
                color: "rgba(153,153,204,1)",
                barBorderRadius: 0
              }
            },
            data: this.remind
          },
          {
            name: "报警",
            type: "bar",
            stack: "总量",
            label: {
              normal: {
                show: true,
                position: "insideRight"
              }
            },
            itemStyle: {
              normal: {
                color: "rgba(255, 153,0,1)",
                barBorderRadius: 0
              }
            },
            data: this.alarm
          },
          {
            name: "超标",
            type: "bar",
            stack: "总量",
            label: {
              normal: {
                show: true,
                position: "insideRight"
              }
            },
            itemStyle: {
              normal: {
                color: "rgba(169,61,93,1)",
                barBorderRadius: 0
              }
            },
            data: this.exceed
          }
        ]
      });
    },
    checkOne(val) {
      console.log(val);
    },
    checkTwo(val) {
      console.log(val);
    },
    // 时间滑块
    formatTooltip(val) {
      return `近${val}天`;
    },
    morechoose() {
      this.$bus.$emit("chooseBank", {
        callback: banks => {
          let banksName = [];
          let banksId = [];
          banks.forEach((item, index) => {
            banksName.push(item.bName);
            banksId.push(item.bId);
          });
          this.banks = banksName.join(",");
          this.banksId = banksId;
        }
      });
    },
    choosezhibiao() {
      this.$bus.$emit("chooseTarget", {
        callback: banks => {
          let banksName = [];
          let banksId = [];
          banks.forEach((item, index) => {
            banksName.push(item.indicatorName);
            banksId.push(item.id);
          });
          this.zhibiaoArr = banksName;
          this.zhibiao = banksName.join(",");
          this.zhibiaoId = banksId;
        }
      });
    },
    queryReset() {
      this.banks = "";
      // 关注
      this.value = "";
      this.zhibiao = "";
      this.time = 3;
      this.typeChek = this.type;
      this.levelChek = this.level;
    },
    queryTable(val = 1) {
      this.currentPage = val;
      let obj = {
        date: this.time,
        bankList: this.banksId,
        warnBank: this.search,
        state: this.value,
        indicatorList: this.zhibiaoArr,
        warnType: this.typeChek,
        userFocusLevel: this.levelChek,
        limit: 10,
        page: val
      };
      this.axios
        .post("warnRecord/findWarnRecord", obj)
        .then(({ data }) => {
          if (data.code == 200) {
            this.tableData = data.data;
            this.total = data.pageInfo.total;
          }
          console.log(data);
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    mange() {
      this.$router.push("/follow");
    },
    daochu() {
      let obj = {
        date: this.time,
        bankList: this.banksId,
        warnBank: this.search,
        state: this.value,
        indicatorList: this.zhibiaoArr,
        warnType: this.typeChek,
        userFocusLevel: this.levelChek
      };
      this.axios
        .post("warnRecord/exportWarnRecord",obj,{responseType: 'blob'})
        .then(res=> {
          console.log(res);
          this.download(res.data,'指标预警信息');
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    download (data, filename) {
        if(!data){
            return
        }
        var blob = new Blob([data], {type: "application/vnd.ms-excel"})
        var url = window.URL.createObjectURL(blob);
        var aLink = document.createElement("a");
        aLink.style.display = "none";
        aLink.href = url;
        aLink.setAttribute("download", decodeURI(filename));
        document.body.appendChild(aLink);
        aLink.click();
        document.body.removeChild(aLink); //下载完成移除元素
        window.URL.revokeObjectURL(url); //释放掉blob对象
    },
    // 分页
    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val;
      this.queryTable(val);
    }
  },
  beforeDestroy: function() {
    this.$bus.$emit("chooseBank");
    this.$bus.$emit("chooseTarget");
  }
};
</script>

<style lang="scss">
#earlywarning {
  [v-cloak] {
    display: none;
  }
  .echartsbox {
    height: 500px;
    background-color: white;
    width: 100%;
    margin-bottom: 40px;
    .circle {
      width: 100%;
      height: 500px;
    }
  }
  .sTitle {
    height: 50px;
    line-height: 50px;
    padding-left: 20px;
    border-bottom: 1px solid #000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: white !important;
    .el-input {
      width: 400px;
      margin-right: 20px;
    }
  }
  .query {
    .queryCon {
      padding: 20px 20px;
      background: white !important;
      .qSeles {
        .xuanze {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          margin-top: 10px;
          .xuanzeCon {
            height: 40px;
            display: flex;
            align-items: center;
            margin-right: 30px;
            .el-input {
              width: 128px;
            }
          }
        }
        .leixing {
          margin-top: 15px;
          .qiek {
            .el-checkbox {
              margin-top: 10px;
              margin-left: 0;
              margin-right: 20px;
            }
          }
        }
        .timezhou {
          margin-top: 20px;
          .el-slider__runway {
            background-color: #c0c2c4;
          }
        }
        .btnAb {
          margin-top: 30px;
          .el-button {
            margin-right: 30px;
          }
        }
      }
    }
    .tablecon {
      padding: 20px 0;
    }
    .pgfy {
      padding: 20px;
      padding-top: 10px;
      text-align: right;
    }
  }
}
</style>
